/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.session.filter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.session.Session;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionContext;
import java.time.Duration;
import java.util.Collections;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.util.Set;

abstract class CafHttpSessionAdapter<S extends Session> implements HttpSession {
    private static final Log logger = LogFactory.getLog(CafHttpSessionAdapter.class);
    private S session;
    private final ServletContext servletContext;
    private boolean invalidated;
    private boolean old;
    private static final HttpSessionContext NOOP_SESSION_CONTEXT = new HttpSessionContext() {
        public HttpSession getSession(String sessionId) {
            return null;
        }

        public Enumeration<String> getIds() {
            return CafHttpSessionAdapter.EMPTY_ENUMERATION;
        }
    };
    private static final Enumeration<String> EMPTY_ENUMERATION = new Enumeration<String>() {
        public boolean hasMoreElements() {
            return false;
        }

        public String nextElement() {
            throw new NoSuchElementException("a");
        }
    };

    CafHttpSessionAdapter(S session, ServletContext servletContext) {
        if (session == null) {
            throw new IllegalArgumentException("session cannot be null");
        } else if (servletContext == null) {
            throw new IllegalArgumentException("servletContext cannot be null");
        } else {
            this.session = session;
            this.servletContext = servletContext;
        }
    }

    S getSession() {
        return this.session;
    }

    public long getCreationTime() {
        this.checkState();
        return this.session.getCreationTime().toEpochMilli();
    }

    public String getId() {
        return this.session.getId();
    }

    public long getLastAccessedTime() {
        this.checkState();
        return this.session.getLastAccessedTime().toEpochMilli();
    }

    public ServletContext getServletContext() {
        return this.servletContext;
    }

    public void setMaxInactiveInterval(int interval) {
        this.session.setMaxInactiveInterval(Duration.ofSeconds((long)interval));
    }

    public int getMaxInactiveInterval() {
        return (int)this.session.getMaxInactiveInterval().getSeconds();
    }

    public HttpSessionContext getSessionContext() {
        return NOOP_SESSION_CONTEXT;
    }

    public Object getAttribute(String name) {
        this.checkState();
        return this.session.getAttribute(name);
    }

    public Object getValue(String name) {
        return this.getAttribute(name);
    }

    public Enumeration<String> getAttributeNames() {
        this.checkState();
        return Collections.enumeration(this.session.getAttributeNames());
    }

    public String[] getValueNames() {
        this.checkState();
        Set<String> attrs = this.session.getAttributeNames();
        return (String[])attrs.toArray(new String[0]);
    }

    public void setAttribute(String name, Object value) {
        this.checkState();
        Object oldValue = this.session.getAttribute(name);
        this.session.setAttribute(name, value);
        if (value != oldValue) {
            if (oldValue instanceof HttpSessionBindingListener) {
                try {
                    ((HttpSessionBindingListener)oldValue).valueUnbound(new HttpSessionBindingEvent(this, name, oldValue));
                } catch (Throwable var6) {
                    logger.error("Error invoking session binding event listener", var6);
                }
            }

            if (value instanceof HttpSessionBindingListener) {
                try {
                    ((HttpSessionBindingListener)value).valueBound(new HttpSessionBindingEvent(this, name, value));
                } catch (Throwable var5) {
                    logger.error("Error invoking session binding event listener", var5);
                }
            }
        }

    }

    public void putValue(String name, Object value) {
        this.setAttribute(name, value);
    }

    public void removeAttribute(String name) {
        this.checkState();
        Object oldValue = this.session.getAttribute(name);
        this.session.removeAttribute(name);
        if (oldValue instanceof HttpSessionBindingListener) {
            try {
                ((HttpSessionBindingListener)oldValue).valueUnbound(new HttpSessionBindingEvent(this, name, oldValue));
            } catch (Throwable var4) {
                logger.error("Error invoking session binding event listener", var4);
            }
        }

    }

    public void removeValue(String name) {
        this.removeAttribute(name);
    }

    public void invalidate() {
        this.checkState();
        this.invalidated = true;
    }

    public boolean isNew() {
        this.checkState();
        return !this.old;
    }

    void markNotNew() {
        this.old = true;
    }

    private void checkState() {
        if (this.invalidated) {
            throw new IllegalStateException("The HttpSession has already be invalidated.");
        }
    }
}